const pool = require('./dbpool')

module.exports = {
    createUser:
        /**
         * 创建一个用户
         * 
         * @param {string} name 用户昵称
         * @param {string} mail 用户邮箱
         * @param {string} pass 用户密码
         */
        function (name, mail, pass) {
            pool.getconnection(function (err, connection) {
                if (err != null)
                    throw new Error('DB UNKNOW ERROR')
                else {
                    var values = [name, pass, mail]
                    connection.query('INSERT INTO `user_table` (`user_name`,`user_pass`,`user_mail`) VALUES (?,?,?)', values,
                        function (err, result) {

                        })
                }
            })
        },
    searchbyMail:
        /**
         * 根据邮箱查找用户
         * 
         * @param {string} mail 邮箱
         * @param {Function} callback 返回方法 
         */
        function (mail, callback) {
            pool.getconnection(function (err, connection) {
                if (err != null)
                    throw new Error('DB UNKNOW ERROR')
                var values = [mail]
                connection.query('SELECT * FROM `user_table` WHERE `user_mail` = ?', values, function (err, result) {
                    callback(result)
                })
            })
        },
    updateById:
        /**
         * 根据信息修改
         * 
         * @param {object} obj 用户对象，包含以下属性 user_name user_pass user_mail token token_over_time user_id
         * @param {Function} callback 回调函数，0异常，1成功
         */
        function (obj, callback) {
            pool.getconnection(function (err, connection) {
                if (err != null)
                    throw new Error('DB UNKNOW ERROR')
                var values = [obj.user_name, obj.user_pass, obj.user_mail, obj.token, obj.token_over_time, obj.user_id]
                connection.query('UPDATE `user_table` SET `user_name` = ? , `user_pass` = ? , `user_mail` = ? , `token` = ? ,' +
                    ' `token_over_time` = ? WHERE `user_id` = ?', values,
                    function (err, result) {
                        if (err != null)
                            callback(0)
                        else
                            callback(1)
                    })
            })
        }

}